from pymt import *
import os
import random
from OpenGL.GL import *
import copy
import Image

current_dir = os.path.dirname(__file__)

class MTExternalContent(MTScatterWidget):

    def __init__(self, type, **kwargs):
        print "MTExternalContent constructed"
        self.type=type
        self.height_max = 800
        self.height_min = 50
        self.width_max = 600
        self.width_min = 160		
        super(MTExternalContent, self).__init__(**kwargs)
    
    def on_touch_down(self,touch):
        if not self.collide_point(*touch.pos):
			return False
	print 'down'
        return MTScatterWidget.on_touch_down(self, touch)

    def on_touch_move (self, touch):
        if not self.collide_point(*touch.pos):
			return False	
		#content can't be outside the windows  
        w = self.get_parent_window()        
        print 'on move'
        self.posX= super(MTExternalContent, self)._get_x()
        self.posY= super(MTExternalContent, self)._get_y()

        if self.posX-(self.width/2) < 0:
			super(MTExternalContent, self)._set_center(center = ((self.width/2),self.posY))
        if self.posY-(self.height/2) < 0:
			super(MTExternalContent, self)._set_center(center = (self.posX,(self.height/2)))
        if self.posX+(self.width/2)> w.width:
			super(MTExternalContent, self)._set_center(center = ((w.width-(self.width/2)),self.posY))
        if self.posY +(self.height/2) > w.height:		
			super(MTExternalContent, self)._set_center(center = (self.posX,(w.height-(self.height/2))))
			
        return MTScatterWidget.on_touch_move(self, touch)

    def on_transform (self, angle, scale, trans, point):
		return MTScatterWidget.on_transform(self, touch)

    def apply_angle_scale_trans(self, angle, scale, trans, point=Vector(0, 0)):
		if(len(self.touches) == 2 and self.type=="picture"):    # change size rather than scale
			old_width=self.width
			old_height=self.height
			self.width *= scale
			self.height *= scale
			
			# check that the widget isn't too small or too large
			if(self.height <= self.height_min ):
				print "height too small"
				self.height = self.height_min
				self.width = old_width
			elif(self.height >= self.height_max):
				print "height too big"			
				self.height = self.height_max
				self.width = old_width				
			if(self.width <= self.width_min):
				print "width too small"			
				self.width = self.width_min
				self.height = old_height				
			elif(self.width >= self.width_max):
				print "width too big"
				self.width = self.width_max
				self.height = old_height				
			scale = 1
			self.dispatch_event('on_transform', angle, scale, trans, point)
		scale=0
		MTScatterWidget.apply_angle_scale_trans(self, angle, scale, trans, point)

    def draw(self):
        MTScatterWidget.draw(self)
